#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <unistd.h>
#include <vector>

using namespace std;

int main(int argc, char *argv[]) {
  if (argc < 3) {
    cerr << "Usage:\n"
         << "  Start: " << argv[0] << " start <type> <name1> <name2>...\n"
         << "  Stop:  " << argv[0] << " stop <key1> <key2>..." << endl;
    return 1;
  }

  vector<string> messages;
  string cmd = argv[1];

  // 构建消息列表
  if (cmd == "start" && argc >= 4) {
    string type = argv[2];
    for (int i = 3; i < argc; ++i) {
      messages.push_back("start " + type + " " + argv[i]); // 每个实例单独消息
    }
  } else if (cmd == "stop" && argc >= 3) {
    string stop_msg = "stop";
    for (int i = 2; i < argc; ++i) {
      stop_msg += " " + string(argv[i]);
    }
    messages.push_back(stop_msg); // 批量停止单条消息
  } else {
    cerr << "Invalid command" << endl;
    return 1;
  }

  // 发送所有消息
  for (const auto &msg : messages) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
      cerr << "Socket creation error" << endl;
      continue;
    }

    sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8080);

    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
      cerr << "Invalid address for message: " << msg << endl;
      close(sock);
      continue;
    }

    if (connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
      cerr << "Connection failed for message: " << msg << endl;
      close(sock);
      continue;
    }

    // 发送消息并检查结果
    if (send(sock, msg.c_str(), msg.size(), 0) < 0) {
      cerr << "Send failed: " << msg << endl;
    } else {
      cout << "Sent: " << msg << endl; // 调试信息
    }
    close(sock);
  }

  return 0;
}